<?php

namespace app\controller\Api\V1\Client\Auth;

use app\helper\AccountBan;
use app\helper\ChannelSdk\Official;
use app\helper\ChannelSdk\Quick;
use app\helper\ChannelSdk\XuTeng;
use app\helper\ChannelSdk\UMark;
use app\helper\ChannelSdk\XieXiao;
use app\helper\Config;
use app\model\AutoTaskRecord;
use app\model\ChannelSdkBind;
use app\model\User;
use Exception;
use Illuminate\Hashing\BcryptHasher;
use support\Request;
use support\Response;

class ChannelSdkController
{

    protected Config $configRe;
    protected Official $officialSqk;
    protected UMark $uMarkSdk;
    protected Quick $quickSdk;
    protected XieXiao $xiqXiaoSdk;
    protected XuTeng $xuTengSdk;
    protected string $platform = 'game';


    public function __construct()
    {
        $this->configRe = Config::getInstance();
        $this->officialSqk = Official::getInstance();
        $this->uMarkSdk = UMark::getInstance();
        $this->quickSdk = Quick::getInstance();
        $this->xiqXiaoSdk = XieXiao::getInstance();
        $this->xuTengSdk = XuTeng::getInstance();
    }


    /**
     * 渠道SDK登录
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function Auth(Request $request): Response
    {

        /**
         * 10000 官方
         * 10002 游码
         * 10003 Quick
         * 10004 XieXiao 合肥协萧
         * 10005 xuTengSdk 栩腾
         */
        $result = match ($request->input('channel')) {
            '10000' => $this->officialSqk->loginAuth($request->input('channel'), $request->input('token')),
            '10002' => $this->uMarkSdk->loginAuth($request->input('platform'), $request->input('uid'), $request->input('token')),
            '10003' => $this->quickSdk->loginAuth($request->input('uid'), $request->input('token')),
            '10004' => $this->xiqXiaoSdk->loginAuth($request->input('uid')),
            '10005' => $this->xuTengSdk->loginAuth($request->input('uid'), $request->input('token')),
            default => ['state' => false, 'message' => '渠道不存在'],
        };
//        dd($result);

        if (!$result['state']) {
            throw new Exception($result['message'], 500);
        }
//        $result['data']['uid'] = '18-257991';

        // 本平台登录流程
        $userInfo = null;
        $isRegister = false;
        $userVerifyInfo = ChannelSdkBind::query()->where('channel_uid', $result['data']['uid'])->where('channel', $request->input('channel'))->first();
//        dd($userVerifyInfo->user);
//        dd($userVerifyInfo->toArray());
        if ($userVerifyInfo) {
            $userInfo = User::query()->where('ulid', $userVerifyInfo->user)->first();
//            dd($userInfo->toArray());
        }

        try {
            if ($userInfo) {
                $userInfo = $userInfo->toArray();
//                dd($userInfo);
            } else {
                $hash = new BcryptHasher();
                $account = GetAccount();
                $userInfo = User::query()->create([
                    'account' => $account,
                    'nickname' => GetNickname(),
                    'avatar' => $this->configRe->Get('user_default_avatar') ?? '',
                    'password' => $hash->make(sha1($account)),
                    'invitation_code' => GetInvitationCode(),
                    'registration_source' => $this->platform,
                    'registration_client' => null,
                    'register_ip' => $request->getRealIp(),
                    'state' => 1,
                ]);
//                dd($userInfo->toArray());
//                var_dump($userInfo['ulid']);

                // 新增用户&渠道关联
                ChannelSdkBind::query()->create([
                    'user' => $userInfo['ulid'],
                    'channel' => $request->input('channel'),
                    'channel_uid' => $result['data']['uid'],
                    'channel_data' => json_encode($result['data']),
                ]);

                $isRegister = true;
            }
        } catch (Exception) {
            throw new Exception('登录失败', 500);
        }

        if ($userInfo['state'] !== 1) {
            throw new Exception('账号已禁用3', 500);
        }

        // 账号封禁状态检查
        $accountBanCheck = AccountBan::getInstance();
        $accountBanCheck->Check($request->input('game_id'), $userInfo['account']);

        AutoTaskRecord::query()->create([
            'label' => 'user-login-game-operation',
            'params' => json_encode([
                'scene' => $isRegister ? 'register' : 'channel-login',
                'user' => $userInfo['ulid'],
                'request' => $request->all(),
                'platform' => $this->platform,
                'ip' => $request->getRealIp(),
            ]),
            'run_time' => time(),
            'state' => 0,
        ]);

        return jsonRe([
            'token' => GenerateLoginToken($userInfo, $request->getRealIp(), $this->platform),
        ]);

    }

}
